/**
 * ECP Web开发 通用导出.
 * Copyright(c) 2012-2020 YGSoft.Inc
 * author:zhengxianwei
 * date:2016-12-27
 */

 define(["jquery","ecp.utils" ,"ecp.component.dialog","ecp.utils.i18n"],function($, utils, $window, locale){
	 
	 var exportLocale = locale.export;
	 /**
	  * 默认参数.
	  */
	 var defaultOption = {
		isCard : true, //单凭模式
		isShowFormat: false, //默认不显示导出格式
		winOption:{
			title:exportLocale.title,
			url : "/grm/ecp/webcore/components/export/export.html",
            showCloseButton:false,
            offClick :true,  //取消点击非模态窗位置关闭窗口
			fade : false,  //取消动画效果
			multilayer : true,  //允许多次嵌套模态窗
//			height: "700px",
            width : "420px",   //模态窗宽度 支持如 100% 600px
            maxHeight : "513px"  //模态窗body最大高度，超过时body内将出现滚动条
		}
	 };
	 
	 /**
	  * 声明EcpExport对象.
	  * @param {Object} control 控件的jQuery对象，即占位符。
	  * @param {option} option 控件的属性对象
	 */
	 var EcpExport = function(control,option){
		 this.init(control,option);
		 this.render();
	 }
	 
	 /**
	  * 通过原型定义相关方法，比如渲染、赋值等等.
	  */
	 EcpExport.prototype = {
			 init: function(control,option){
				 this.control = control;
				 if(!option){
					 option = {};
				 }
				 this.option = option;
			 },
			 render: function(){
				 	var me = this;
				 	var opt = $.extend(true,{},defaultOption.winOption,me.option.winOption,{
					 	callback:function(container){
					 			me.winContianer = container;
					 			//国际化
			                	utils.loadLocale(exportLocale,container);
	//		    				utils.domAttrI18n(notEmpty, container, "title");
			    				utils.domAttrI18n(exportLocale, container, "placeholder");
			                	me.bindEvent();
		                },
		                otherButtons : [exportLocale.cancel, exportLocale.confirm],
		                otherButtonStyles : ['btn-default', 'btn-primary'],
		                clickButton:function(sender, modal, index){
		                	if(index == 1){  //确定按钮
		                		if(me.validate()){
		                			me.doExport();
	                				modal.modal("hide");
		                		}
		                	}
		                	if(index == 0){  //取消按钮
		                		modal.modal("hide");
		                	}
		                }
				 });
				 me.winContainer = $window.window(opt);
			 },
			 
			 /**
			  * 导出. 
			  */
			 doExport: function(){
				 var me = this,
				 	 callback = me.option.exportCallBack,
				 	 bool = false;
				 if(callback && $.isFunction(callback)){
					 var exportRange = $("input[name='range']:checked", me.winContainer).val(),
			 		 	exportMode = $("input[name='mode']:checked", me.winContainer).val(),
			 		 	exportFileType = $("input[name='fileType']:checked", me.winContainer).val(),
			 		 	exportFormat = $("input[name='format']:checked", me.winContainer).val(),
			 		 	curRangeInput = $("#curRangeInput", me.winContainer).val().trim();
		 		 	 if($("input[name='range']:disabled", me.winContainer).length === 3){
		 		 		exportRange = "";
		 		 		curRangeInput = "";
		 		 	 }
		 		 	 if($("#exportFormat", me.winContainer).css("display") == "none"){
		 		 		exportFormat = "";
		 		 	 }
			 		 var opt = {
							 range : exportRange,
							 rangeInput : curRangeInput,
							 mode : exportMode,
							 fileType : exportFileType,
							 format : exportFormat
				 	 };
					 callback.call(me,opt);
				 }
				 return bool;
			 },
			 
			 /**
			  * 校验.
			  */
			 validate: function(){
				var me = this,
					opt = me.option,
					exportRange = $("input[name='range']:checked", me.winContainer).val(),  // 当前： current, 全部：all, 范围：range
					exportMode = $("input[name='mode']:checked", me.winContainer).val(),
					exportFormat = $("#exportFormat", me.winContainer).val();  //xls
				//导出数据且按范围导出
				if(exportMode == 0 &&  exportRange == 2){
					var pageNum = opt.pageNum || 0;
					var curRangeInput = $("#curRangeInput", me.winContainer);
					exportRange = curRangeInput.val().trim();  //1-2, 2- 如果省略结束页码，end转为-1
					if(exportRange===""){
						utils.notify(exportLocale.notEmpty);
						return;
					}
					exportRange = exportRange.replace(/\s/g,"");
					if(!(/^[0-9]{0,5}([-]?[0-9]{0,6})?$/.test(exportRange))){
						utils.notify(exportLocale.rangeError);
//							$.ecp.utils.setFocusPosition(pageRangeUI.control,true);
						return; 
					}
					exportRange = exportRange.split("-");
					var endPage=-1;
					if(exportRange.length==1){
					  endPage = +exportRange[0];
					}else if(exportRange[1]===""){
					  endPage = -1;
					}else{
					  endPage = +exportRange[1];
					}
					exportRange = {begin:exportRange[0] ? +exportRange[0] : 1 , 
									end: endPage};
									
					if(exportRange.begin > exportRange.end && exportRange.end != -1 ){
						utils.notify(exportLocale.beginDyEnd);
							utils.setFocusPosition(curRangeInput,true);
						return;
					}
					if(exportRange.begin<=0 || (pageNum>0 && (exportRange.begin > pageNum || exportRange.end > pageNum))){
						utils.notify(exportLocale.ccRange);
							utils.setFocusPosition(curRangeInput,true);
						return;
					}
				}
				return true;
			 },
			 
			 /**
			  * 绑定事件.
			  */
			 bindEvent: function(){
				 var me = this,
				 	 opt = me.option,
				 	 exportMode = $("#exportMode", me.winContainer),
				 	 exportRange = $("#exportRange", me.winContainer),
				 	 range = exportRange.find("input[type='radio']"),
				 	 curRangeInput = $("#curRangeInput", me.winContainer),
				 	 exportType = $("#exportType", me.winContainer);
				 opt.rangeDisable = false;
				 //option配置rangeDisable为true表示导出范围不可用
				 if(opt.rangeDisable === true){
					 range.attr("disabled","disabled");
				 }
				 //option配置rangeHide为true表示导出范围隐藏
				 if(opt.rangeHide === true){
					 exportRange.hide();
				 }
				 //是否显示导出格式
				 if(opt.showExportFormat === true){
					 $("#exportFormat",  me.winContainer).show();
				 }
				 //导出模式
				 exportMode.off("click").on("click",function(){
					 var pdf = exportType.find("input[value='3']");
					 //模板
					 if($("input[name='mode']:checked", me.winContainer).val() == 1 || opt.template === true){
						 range.attr("disabled","disabled");
//						 curRangeInput.attr("disabled","disabled");
						 //如果选中模板并且已选中pdf，那么就选中第一个导出类型
						 if($("input[name='fileType']:checked", me.winContainer).val() == 3){
							 exportType.find("input[value='0']").click();
						 }
						//如果选中模板，pdf要置灰
						 pdf.attr("disabled","disabled");
					 }else{
						 //数据
						 if(opt.rangeDisable !== true){
							 range.removeAttr("disabled");
						 }
						 pdf.removeAttr("disabled");
					 }
				 })
				 //导出范围
				 exportRange.off("click").on("click",function(){
					 if($("input[name='range']:checked", me.winContainer).val() == 2){
						 curRangeInput.removeAttr("disabled");
					 }else{
						 curRangeInput.attr("disabled",true);
					 }
				 })
				 //option配置template为true表示只导出模板
				 if(opt.template === true){
					 //exportMode.find("input[value='0']").attr("disabled","disabled");
					 $(exportMode.find(".radio").get(0)).hide();
					 exportMode.find("input[value='1']").click();
				 }else if(opt.template === false){
					 //exportMode.find("input[value='1']").attr("disabled","disabled");
					 $(exportMode.find(".radio").get(1)).hide();
				 }
				 //隐藏导出类型：hideExportType: pdf\wps\excel2003\excel2007 分别表示3,2,1,0；值用字符串表示，多个用逗号隔开
				 if(opt.hideExportType){
					var ets = opt.hideExportType.split(",");
					var radios = exportType.find(".radio");
					$.each(radios,function(i,obj){
						if($.inArray(i+"",ets)>=0){
							$(this).hide();
						}
					})
				 }
			 }
	 };
	 
	 (function($) {
		var old = $.fn.ecpExport;
		/**
		 * 集成到jquery中，暴露ecpExport接口，渲染下拉控件
		 * @param {Object | String | Boolean} option
		 *  为object时表示渲染控件需要的参数;
		 *  为string时表示调用控件的方法；
		 *  为boolean时表示获取控件对象
		 */
		$.fn.ecpExport = function(option){
			var me = this;
			if(!me || me.length === 0){
				if(window.console){
					window.console.error("ecp.component.ecpExport"+i18n.select.renderError);
				}
				return;
			}
			option = option || {};
			var type = typeof(option);
			//如果第一个参数传入的是对象或空则初始化空件，如果传入的是字符串，则认为是调用里面的内部方法。
			if (type === "object") {
				var ess = [];
				this.each(function() {
					var instanceOption = $.extend({}, option, true);
					var instance = new EcpExport($(this), instanceOption);
					this.ecpExport = instance;
					ess.push(instance);
				});
				if(ess.length === 1){
					ess = ess[0];
				}
				return ess;
			} else if (type === "string") {
				var args = Array.prototype.slice.call(arguments, 1);
				if (EcpExport.prototype[option]) {
					return EcpExport.prototype[option].call(args);
				}
			} else if (option === true) {
				return me[0] && me[0].ecpExport;
			}
		};
		$.fn.ecpExport.Constructor = EcpExport;
		$.fn.ecpExport.noConflict = function() {
			$.fn.ecpExport = old;
			return this;
		};
	 }(jQuery));
	 return EcpExport;
 });